/*
 * Label.java
 *
 * Created on 2004/11/25 +0900
 *
 * $Revision: 59 $
 * $Date: 2008-12-28 19:22:21 +0000 (Sun, 28 Dec 2008) $
 */

package org.gikolet.framework.ui;

/**
 * @author Tetsutaro (latest modification by $Author: tetsutaro.ss $)
 * @version $Revision: 59 $ $Date: 2008-12-28 19:22:21 +0000 (Sun, 28 Dec 2008) $
 */
public class Label extends Widget {
    public static final String PROPERTY_ALIGNMENT = "alignment";

    public static final int LEFT = 0;
    public static final int CENTER = 1;
    public static final int RIGHT = 2;

    private String oldText = "";

    private int alignment;

    public Label() {
	this("", LEFT);
    }

    public Label(String text) {
	this(text, LEFT);
    }

    public Label(int horizontalAlignment) {
	this(null, horizontalAlignment);
    }

    public Label(String text, int alignment) {
	super(false);

	setText(text);
	this.alignment = alignment;
    }

    public final int getAlignment() {
	return this.alignment;
    }

    public final void setAlignment(int alignment) {
	this.alignment = alignment;

	firePropertyChanged(PROPERTY_ALIGNMENT);
    }

    public Dimension getPreferredSize(int hintWidth, int hintHeight) {
	Font font = getFont();
	if (font != null) {
	    return new Dimension(font.stringWidth(getText()), font.getHeight());
	}
	return super.getPreferredSize(hintWidth, hintHeight);
    }

    protected void paintWidget(Graphics g) {
	String text = getText();
	Font font = g.getFont();
	int width = getWidth();
	int height = getHeight();

	int x = 0;
	int minW = font.stringWidth(text);

	if (this.alignment == CENTER) {
	    x = (width - minW) / 2;

	} else if (this.alignment == RIGHT) {
	    x = width - minW;
	}
	g.drawString(text, x, (height - font.getHeight()) / 2);
    }

    /**
     * @see org.gikolet.framework.ui.Widget#firePropertyChanged(java.lang.String)
     */
    protected void firePropertyChanged(String propertyName) {
	if (PROPERTY_TEXT.equals(propertyName)) {
	    String text = getText();
	    Font font = getFont();
	    if (font != null
		    && font.stringWidth(text) != font.stringWidth(this.oldText)) {
		revalidate();
	    }
	    this.oldText = text;

	    repaint();

	} else if (PROPERTY_ALIGNMENT.equals(propertyName)) {
	    repaint();
	}
	super.firePropertyChanged(propertyName);
    }
}
